from flask_httpauth import HTTPBasicAuth
from flask import g, jsonify
from  ..models import *
from . import repair
from .errors import unauthorized


auth = HTTPBasicAuth()

@auth.error_handler
def auth_error():
    return unauthorized('Invalid credentials')

@auth.verify_password
def verify_password(username_or_token, password):
    if password == '':
        g.current_user = User.verify_auth_token(username_or_token)
        g.token_used = True
        return g.current_user is not None
    user = User.query.filter_by(username=username_or_token).first()
    if not user:
        return False
    g.current_user = user
    g.token_used = False
    return user.verify_password(password)

@repair.route('/token')
@auth.login_required
def get_token():
    if g.token_used:
        return unauthorized('Invalid credentials')
    expiration = 3600
    token_json = {
        'token': g.current_user.generate_auth_token(expiration=expiration).decode('ascii'),
        'expiration': expiration
    }
    return jsonify(token_json)